/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package com.isisufes.joinus.appserver;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserMap extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String GET_USERS_WITH_LOCATION =
		"SELECT A.firstName || ' ' || A.lastName AS fullName, A.gpsLat, A.gpsLng FROM profile A "
		+ " INNER JOIN joinscampaign B ON B.idprofile = A.idprofile AND B.idcampaign = ? "
		+ " WHERE (NOW()-gpsLastUpdate) < '15:00'; ";
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Pegando o parâmetro necessário
		int campaignId;
		try{
			campaignId = Integer.parseInt(request.getParameter("campaignId"));
		}catch(Exception e){
			response.getOutputStream().println("Argumento campaignId não encontrado!");
			return;
		}
		
		DBConn.init();
		PreparedStatement sql = DBConn.stmt(GET_USERS_WITH_LOCATION);
		ResultSet rs;
		StringBuilder sb = new StringBuilder();
		try{
			sql.setInt(1, campaignId);
			rs = sql.executeQuery();
			
			sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
			sb.append("<GeoObjects>\n");
			while(rs.next()){
				String name = rs.getString("fullname");
				Double lat = rs.getDouble("gpslat");
				Double lng = rs.getDouble("gpslng");
				
				sb.append("\t<GeoObject lat=\"" + lat + "\" lon=\"" + lng + "\" label=\"" + name + "\" type=\"user\" />\n");
			}
			sb.append("</GeoObjects>\n");
			response.getOutputStream().print(sb.toString());
			
		}catch(Exception e){
			response.getOutputStream().print("Erro! Erro não especificado no banco de dados!");
		}
	}

}
